import {
  DynamicInstanceConfig,
  IPSAppCounterRef,
  IPSAppView,
  IPSAppViewLogic,
  IPSControl,
} from '@ibiz/dynamic-model-api';
import { Subject, Subscription } from 'rxjs';
import { LogUtil } from '../../../util';
import { AppCtrlEventEngine, AppTimerEngine, AppViewEventEngine } from '../../../engine';
import {
  IAppViewControllerBase,
  IParam,
  IUIDataParam,
  IUIEnvironmentParam,
  IAppViewHooks,
  AppCtrlEvents,
  IViewStateParam,
  MobToolbarEvents,
  AppViewEvents,
} from '../../../interface';
import { AppViewHooks } from '../../hooks';
import { AppViewLogicUtil } from '../../utils';
import { GetModelService } from '../../../app';
import { AppUIControllerBase } from '../base';

/**
 * 视图控制器基类
 *
 * @export
 * @class AppViewControllerBase
 */
export class AppViewControllerBase extends AppUIControllerBase implements IAppViewControllerBase {
  /**
   * @description 视图模型路径
   * @protected
   * @type {string}
   * @memberof AppViewControllerBase
   */
  protected viewPath: string = '';

  /**
   * @description 视图默认加载
   * @type {boolean}
   * @memberof AppViewControllerBase
   */
  public isLoadDefault: boolean = true;

  /**
   * @description 是否显示视图标题栏
   * @type {boolean}
   * @memberof AppViewControllerBase
   */
  public isShowCaptionBar: boolean = true;

  /**
   * @description 视图打开模式
   * @type {('ROUTE' | 'MODEL' | 'EMBEDDED')}
   * @memberof AppViewControllerBase
   */
  public viewShowMode: 'ROUTE' | 'MODEL' | 'EMBEDDED' = 'ROUTE';

  /**
   * @description 视图钩子对象
   * @type {IAppViewHooks}
   * @memberof AppViewControllerBase
   */
  public hooks: IAppViewHooks = new AppViewHooks();

  /**
   * @description 应用上下文
   * @type {IParam}
   * @memberof AppViewControllerBase
   */
  public context!: IParam;

  /**
   * @description 数据部件名称
   * @type {string}
   * @memberof AppViewControllerBase
   */
  public xDataControlName!: string;

  /**
   * @description 视图参数
   * @type {IParam}
   * @memberof AppViewControllerBase
   */
  public viewParam!: IParam;

  /**
   * @description 视图导航数据
   * @type {Array<IParam>}
   * @memberof AppViewControllerBase
   */
  public navDatas!: Array<IParam>;

  /**
   * @description 视图操作参数集合
   * @type {*}
   * @memberof AppViewControllerBase
   */
  public viewCtx: any = {};

  /**
   * @description 视图传递对象
   * @type {Subject<IViewStateParam>}
   * @memberof AppViewControllerBase
   */
  public viewState!: Subject<IViewStateParam>;

  /**
   * @description 视图模型对象
   * @type {IPSAppView}
   * @memberof AppViewControllerBase
   */
  public viewInstance!: IPSAppView;

  /**
   * @description 视图模型
   * @type {IPSAppView}
   * @memberof AppViewControllerBase
   */
  public modelData?: any;

  /**
   * @description 预览数据
   * @type {IPSAppView}
   * @memberof AppViewControllerBase
   */
  public previewData: IParam[] = [];

  /**
   * @description 自定义视图导航上下文集合
   * @protected
   * @type {*}
   * @memberof AppViewControllerBase
   */
  protected customViewNavContexts: any = {};

  /**
   * @description 自定义视图导航参数集合
   * @protected
   * @type {*}
   * @memberof AppViewControllerBase
   */
  protected customViewParams: any = {};

  /**
   * @description 模型服务对象
   * @type {*}
   * @memberof AppViewControllerBase
   */
  public modelService: any;

  /**
   * @description 视图消息服务
   * @type {*}
   * @memberof AppViewControllerBase
   */
  public viewMessageService: any;

  /**
   * @description 视图状态订阅对象
   * @type {(Subscription | undefined)}
   * @memberof AppViewControllerBase
   */
  public viewStateEvent: Subscription | undefined;

  /**
   * @description 计数器服务对象集合
   * @type {Array<any>}
   * @memberof AppViewControllerBase
   */
  public counterServiceArray: Array<any> = [];

  /**
   * @description 视图是否完成挂载
   * @type {boolean}
   * @memberof AppViewControllerBase
   */
  public hasViewMounted: boolean = false;

  /**
   * @description 视图是否完成加载
   * @type {boolean}
   * @memberof AppViewControllerBase
   */
  public viewIsLoaded: boolean = false;

  /**
   * @description 界面触发逻辑Map
   * @type {Map<string, any>}
   * @memberof AppViewControllerBase
   */
  public viewTriggerLogicMap: Map<string, any> = new Map();

  /**
   * @description 挂载状态集合
   * @type {Map<string, boolean>}
   * @memberof AppViewControllerBase
   */
  public mountedMap: Map<string, boolean> = new Map();

  /**
   * @description 视图部件引用控制器集合
   * @type {Map<string, IParam>}
   * @memberof AppViewControllerBase
   */
  public ctrlRefsMap: Map<string, IParam> = new Map();

  /**
   * @description 视图引擎
   * @type {*}
   * @memberof AppViewControllerBase
   */
  public engine: any;

  /**
   * @description 获取顶层视图
   * @return {*}
   * @memberof AppViewControllerBase
   */
  public getTopView() {
    return this.viewCtx.topview;
  }

  /**
   * @description 获取父级视图
   * @return {*}
   * @memberof AppViewControllerBase
   */
  public getParentView() {
    return this.viewCtx.parentview;
  }

  /**
   * @description 获取视图激活数据
   * @return {*}  {(IParam | null)}
   * @memberof AppViewControllerBase
   */
  public getData(): IParam | null {
    return this.xDataControlName ? this.ctrlRefsMap.get(this.xDataControlName)?.getData() : null;
  }

  /**
   * @description 获取视图激活数据集
   * @return {*}  {(Array<IParam> | null)}
   * @memberof AppViewControllerBase
   */
  public getDatas(): Array<IParam> | null {
    return this.xDataControlName ? this.ctrlRefsMap.get(this.xDataControlName)?.getDatas() : [];
  }

  /**
   * @description 获取逻辑UI数据
   * @param {(Array<IParam> | null)} data 数据集合
   * @return {*}  {IUIDataParam}
   * @memberof AppViewControllerBase
   */
  public getUIDataParam(data: Array<IParam> | null): IUIDataParam {
    return {
      data: data ? data : this.getDatas(),
      navContext: this.context,
      navParam: this.viewParam,
      navData: this.navDatas,
      sender: this,
    };
  }

  /**
   * @description 获取逻辑环境数据
   * @return {*}  {IUIEnvironmentParam}
   * @memberof AppViewControllerBase
   */
  public getUIEnvironmentParam(): IUIEnvironmentParam {
    return {
      app: this.viewCtx?.app,
      view: this.viewCtx?.view,
      ctrl: null,
      parentDeCodeName: null,
    };
  }

  /**
   * @description 通过名称获取部件
   * @param {string} name 部件名称
   * @return {*}  {(IParam | undefined)}
   * @memberof AppViewControllerBase
   */
  public getCtrlByName(name: string): IParam | undefined {
    return this.ctrlRefsMap.get(name);
  }

  /**
   * Creates an instance of AppViewControllerBase.
   * @param {*} opts 构造参数
   * @memberof AppViewControllerBase
   */
  constructor(opts: any) {
    super(opts);
    this.initInputData(opts);
  }

  /**
   * @description 初始化输入数据
   * @param {*} opts 输入数据
   * @memberof AppViewControllerBase
   */
  public initInputData(opts: any) {
    this.viewPath = opts.viewPath;
    this.viewShowMode = opts?.viewShowMode ? opts.viewShowMode : 'ROUTE';
    this.isLoadDefault = opts?.isLoadDefault != undefined ? opts.isLoadDefault : true; 
    this.isShowCaptionBar = opts?.isShowCaptionBar != undefined ? opts.isShowCaptionBar : true;
    this.modelData = opts.modelData;
    this.previewData = opts.previewData;
    if (!this.viewState) {
      if (opts && opts.viewState) {
        this.viewState = opts.viewState;
      } else {
        this.viewState = new Subject();
      }
    }
  }

  /**
   * @description 视图初始化
   * @return {*}
   * @memberof AppViewControllerBase
   */
  public async viewInit() {
    await this.initModelService();
    await this.initViewInstance();
    this.viewBasicInit();
    this.hooks.modelLoaded.callSync({ arg: this.viewInstance });
    this.initMountedMap();
    this.initViewCtx();
    await this.initViewMessageService();
    await this.initCounterService();
    await this.initAppDataService();
    await this.initAppUIService();
    await this.initQuickGroup();
    await this.initViewLogic();
    this.viewIsLoaded = true;
    setTimeout(() => {
      this.setIsMounted();
      // 处理视图定时器逻辑
      this.handleTimerLogic();
    }, 0);
    return this.viewIsLoaded;
  }

  /**
   * @description 视图基础数据初始化
   * @memberof AppViewControllerBase
   */
  public viewBasicInit() {
    this.customViewNavContexts = this.viewInstance?.getPSAppViewNavContexts() || [];
    this.customViewParams = this.viewInstance?.getPSAppViewNavParams() || [];
    if (this.viewState) {
      this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }: IViewStateParam) => {
        if (!Object.is(tag, this.viewInstance.codeName)) {
          return;
        }
        if (Object.is(action, 'save')) {
          if (this.xDataControlName) {
            this.viewState.next({ tag: this.xDataControlName, action: 'save', data: data });
          } else {
            this.hooks.event.callSync({
              viewName: this.viewInstance?.codeName,
              action: 'save',
              data: data,
            });
          }
        }
        if (Object.is(action, 'refresh')) {
          this.refresh(data);
        }
        if (Object.is(action, 'load')) {
          if (this.engine) {
            this.engine.load(data);
          } else {
            this.viewState.next({ tag: this.xDataControlName, action: 'load', data: data});
          }
        }
      });
    }
  }

  /**
   * @description 初始化模型服务
   * @memberof AppViewControllerBase
   */
  public async initModelService() {
    if (App.isPreviewMode()) {
      return;
    }
    try {
      this.modelService = await GetModelService(this.context);
    } catch (error) {
      await this.initSandBoxInst(this.context);
      this.modelService = await GetModelService(this.context);
    }
  }

  /**
   * @description 初始化视图实例
   * @memberof AppViewControllerBase
   */
  public async initViewInstance() {
    if (App.isPreviewMode() && this.modelData) {
      this.viewInstance = this.modelData as IPSAppView;
      return;
    }
    if (this.viewPath && this.modelService) {
      this.viewInstance = (await this.modelService.getPSAppView(this.viewPath)) as IPSAppView;
      // 视图部件数据加载
      if (this.viewInstance.getPSControls()) {
        for (const control of this.viewInstance.getPSControls() as IPSControl[]) {
          await control.fill();
        }
      }
      // 视图应用实体加载
      await this.viewInstance?.getPSAppDataEntity?.()?.fill();
    }
  }

  /**
   * @description 初始化挂载状态集合
   * @memberof AppViewControllerBase
   */
  public initMountedMap() {
    const controls = this.viewInstance?.getPSControls?.();
    controls?.forEach((item: any) => {
      if (
        item.controlType == 'TOOLBAR' ||
        item.controlType == 'SEARCHBAR' ||
        item.controlType == 'CAPTIONBAR' ||
        item.controlType == 'DATAINFOBAR'
      ) {
        this.mountedMap.set(item.name, true);
      } else {
        this.mountedMap.set(item.name, false);
      }
    });
    this.mountedMap.set('self', false);
  }

  /**
   * @description 初始化视图操作参数
   * @param {*} [args] 视图操作参数
   * @memberof AppViewControllerBase
   */
  public initViewCtx(args?: any): void {
    if (App.isPreviewMode()) {
      return;
    }
    this.viewCtx = { viewNavContext: this.context, viewNavParam: this.viewParam };
    // 处理全局参数
    if (!App.getStore().get('appGlobal')) {
      App.getStore().set('appGlobal', {});
    }
    this.viewCtx['appGlobal'] = App.getStore().get('appGlobal');
    // 处理顶层路由全局参数
    if (App.getStore().get(`routeViewGlobal${this.context.srfsessionid}`)) {
      this.viewCtx['routeViewGlobal'] = App.getStore().get(`routeViewGlobal${this.context.srfsessionid}`);
    } else {
      App.getStore().set(`routeViewGlobal${this.context.srfsessionid}`, {});
      this.viewCtx['routeViewGlobal'] = App.getStore().get(`routeViewGlobal${this.context.srfsessionid}`);
    }
    this.viewCtx['viewGlobal'] = {};
    this.viewCtx['viewNavData'] = {};
    this.viewCtx['app'] = App;
    this.viewCtx['view'] = this;
    // 处理顶层视图
    if (!Object.is(this.viewShowMode, 'ROUTE')) {
      // 嵌入视图
      this.viewCtx['topview'] = App.getStore().get(`topview${this.context.srfsessionid}`);
    } else {
      // 顶层路由视图
      App.getStore().set(`topview${this.context.srfsessionid}`, this);
      this.viewCtx['topview'] = this;
    }
    // 处理父层视图
    if (this.context && this.context.parentviewpath) {
      if (App.getStore()) {
        this.viewCtx['parentview'] = App.getStore().get(`parentview${this.context.parentviewpath}`);
      } else {
        this.viewCtx['parentview'] = null;
      }
    } else {
      this.viewCtx['parentview'] = null;
    }
    if (this.viewInstance && this.viewInstance.modelPath) {
      if (App.getStore()) {
        App.getStore().set(`parentview${this.viewInstance.modelPath}`, this);
      }
      Object.assign(this.context, { parentviewpath: this.viewInstance.modelPath });
    }
  }

  /**
   * @description 初始化视图消息服务
   * @memberof AppViewControllerBase
   */
  public async initViewMessageService() {
    const viewMsgGroup = this.viewInstance?.getPSAppViewMsgGroup?.();
    if (viewMsgGroup) {
      this.viewMessageService = App.getViewMSGService();
      await this.viewMessageService.loaded(viewMsgGroup, this.context, this.viewParam);
    }
  }

  /**
   * @description 初始化计数器服务
   * @memberof AppViewControllerBase
   */
  public async initCounterService() {
    if (App.isPreviewMode()) {
      return;
    }
    const appCounterRef: Array<IPSAppCounterRef> = this.viewInstance.getPSAppCounterRefs() || [];
    if (appCounterRef && appCounterRef.length > 0) {
      for (const counterRef of appCounterRef) {
        const counter = counterRef.getPSAppCounter?.();
        if (counter) {
          await counter.fill(true);
          const counterService = App.getCounterService();
          await counterService.loaded(counter, { navContext: this.context, navViewParam: this.viewParam });
          const tempData: any = { id: counterRef.id, path: counter.modelPath, service: counterService };
          this.counterServiceArray.push(tempData);
        }
      }
    }
  }

  /**
   * @description 引擎初始化
   * @param {*} [opts={}] 初始化参数
   * @memberof AppViewControllerBase
   */
  public engineInit(opts: any = {}) {}

  /**
   * @description 初始化实体服务对象
   * @memberof AppViewControllerBase
   */
  public async initAppDataService() {}

  /**
   * @description 初始化应用界面服务
   * @memberof AppViewControllerBase
   */
  public async initAppUIService() {}

  /**
   * @description 设置已经绘制完成状态
   * @param {string} [name='self'] 部件名
   * @param {*} [data] 数据
   * @memberof AppViewControllerBase
   */
  public setIsMounted(name: string = 'self', data?: any) {
    this.mountedMap.set(name, true);
    if (data) {
      this.ctrlRefsMap.set(name, data);
    }
    if ([...this.mountedMap.values()].indexOf(false) == -1) {
      // 执行viewMounted
      if (!this.hasViewMounted) {
        this.viewMounted();
      }
    }
  }

  /**
   * @description 视图挂载
   * @memberof AppViewControllerBase
   */
  public viewMounted() {
    // 设置挂载状态
    this.hasViewMounted = true;
    if (this.engine) {
      this.engineInit();
    }
    this.hooks.mounted.callSync({ arg: this });
    this.viewEvent(AppViewEvents.MOUNTED);
  }

  /**
   * @description 视图销毁
   * @memberof AppViewControllerBase
   */
  public async viewDestroy() {
    if (Object.is(this.viewShowMode, 'ROUTE')) {
      if (App.getStore()) {
        // 清除顶层路由参数
        App.getStore().delete(`routeViewGlobal${this.context.srfsessionid}`);
        // 清除顶层视图
        App.getStore().delete(`topview${this.context.srfsessionid}`);
      }
    }
    // 清除当前视图
    if (App.getStore()) {
      if (this.viewInstance && this.viewInstance.modelPath) {
        App.getStore().delete(`parentview${this.viewInstance.modelPath}`);
      }
    }
    // 销毁计数器定时器
    if (this.counterServiceArray && this.counterServiceArray.length > 0) {
      this.counterServiceArray.forEach((item: any) => {
        if (item?.service?.destroyCounter && item.service.destroyCounter instanceof Function) {
          item.service.destroyCounter();
        }
      });
    }
    // 销毁逻辑定时器
    this.destroyLogicTimer();
    // 取消订阅
    if (this.viewStateEvent) {
      this.viewStateEvent.unsubscribe();
    }
    this.cancelSubscribe();
  }

  /**
   * @description 计数器刷新
   * @memberof AppViewControllerBase
   */
  public counterRefresh() {
    if (this.counterServiceArray && this.counterServiceArray.length > 0) {
      this.counterServiceArray.forEach((item: any) => {
        const counterService = item.service;
        if (
          counterService &&
          counterService.refreshCounterData &&
          counterService.refreshCounterData instanceof Function
        ) {
          counterService.refreshCounterData(this.context, this.viewParam);
        }
      });
    }
  }

  /**
   * @description 初始化沙箱实例
   * @param {*} args 初始化参数
   * @memberof AppViewControllerBase
   */
  public async initSandBoxInst(args: any) {
    if (args && args.srfsandboxtag) {
      // const tempSandboxInst: SandboxInstance = new SandboxInstance(args);
      // await tempSandboxInst.initSandBox();
    }
  }

  /**
   * @description 处理自定义视图导航数据
   * @param {IParam} context 上下文
   * @param {IParam} viewParam 视图参数
   * @memberof AppViewControllerBase
   */
  public handleCustomViewData(context: IParam, viewParam: IParam) {
    this.handleviewRes();
    if (this.customViewNavContexts.length > 0) {
      this.customViewNavContexts.forEach((item: any) => {
        const tempContext: any = {};
        const curNavContext: any = item;
        this.handleCustomDataLogic(context, viewParam, curNavContext, tempContext, item.key);
        Object.assign(context, tempContext);
      });
    }
    if (this.customViewParams.length > 0) {
      this.customViewParams.forEach((item: any) => {
        const tempParam: any = {};
        const curNavParam: any = item;
        this.handleCustomDataLogic(context, viewParam, curNavParam, tempParam, item.key);
        Object.assign(viewParam, tempParam);
      });
    }
  }

  /**
   * @description 处理其他数据(多实例)
   * @param {IParam} context 上下文
   * @param {IParam} viewParam 视图参数
   * @memberof AppViewControllerBase
   */
  public handleOtherViewData(context: IParam, viewParam: IParam) {
    const appEnvironment = App.getEnvironment();
    if (appEnvironment?.bDynamic && this.modelService) {
      const dynainstParam: DynamicInstanceConfig = this.modelService.getDynaInsConfig();
      if (dynainstParam) {
        Object.assign(viewParam, { srfinsttag: dynainstParam.instTag, srfinsttag2: dynainstParam.instTag2 });
      }
    }
  }

  /**
   * @description 处理指定视图控制关系将父键转为父实体上下文
   * @memberof AppViewControllerBase
   */
  public async handleviewRes() {}

  /**
   * @description 处理自定义视图数据逻辑
   * @param {IParam} context 上下文
   * @param {IParam} viewParam 视图参数
   * @param {*} curNavData 当前导航数据
   * @param {*} tempData 当前数据
   * @param {string} item 数据项名称
   * @memberof AppViewControllerBase
   */
  public handleCustomDataLogic(context: IParam, viewParam: IParam, curNavData: any, tempData: any, item: string) {
    // 直接值直接赋值
    if (curNavData.rawValue) {
      if (Object.is(curNavData.value, 'null') || Object.is(curNavData.value, '')) {
        Object.defineProperty(tempData, item.toLowerCase(), {
          value: null,
          writable: true,
          enumerable: true,
          configurable: true,
        });
      } else {
        Object.defineProperty(tempData, item.toLowerCase(), {
          value: curNavData.value,
          writable: true,
          enumerable: true,
          configurable: true,
        });
      }
    } else {
      // 先从导航上下文取数，没有再从导航参数（URL）取数，如果导航上下文和导航参数都没有则为null
      if (context[curNavData.value.toLowerCase()] != null) {
        Object.defineProperty(tempData, item.toLowerCase(), {
          value: context[curNavData.value.toLowerCase()],
          writable: true,
          enumerable: true,
          configurable: true,
        });
      } else {
        if (viewParam[curNavData.value.toLowerCase()] != null) {
          Object.defineProperty(tempData, item.toLowerCase(), {
            value: viewParam[curNavData.value.toLowerCase()],
            writable: true,
            enumerable: true,
            configurable: true,
          });
        } else {
          Object.defineProperty(tempData, item.toLowerCase(), {
            value: null,
            writable: true,
            enumerable: true,
            configurable: true,
          });
        }
      }
    }
  }

  /**
   * @description 处理部件事件
   * @param {string} controlname 部件名称
   * @param {string} action 部件行为
   * @param {*} data 数据
   * @memberof AppViewControllerBase
   */
  public handleCtrlEvent(controlname: string, action: string, data: any) {
    switch (action) {
      case AppCtrlEvents.MOUNTED:
        this.setIsMounted(controlname, data);
        break;
      case AppCtrlEvents.CLOSE:
        this.closeView(data);
        break;
      case MobToolbarEvents.TOOLBAR_CLICK:
        this.handleToolBarClick(data.tag, data.event);
        break;
      default:
        // 部件事件
        if (controlname && action) {
          if (this.viewTriggerLogicMap.get(`${controlname.toLowerCase()}-${action.toLowerCase()}`)) {
            const ctrlEventLogic = this.viewTriggerLogicMap.get(`${controlname.toLowerCase()}-${action.toLowerCase()}`);
            ctrlEventLogic
              .executeAsyncUILogic({ arg: data, utils: this.viewCtx, environments: this.getUIEnvironmentParam() })
              .then((args: any) => {
                if (args && args?.hasOwnProperty('srfret') && !args.srfret) {
                  return;
                }
                if (this.engine) {
                  this.engine.onCtrlEvent(controlname, action, data);
                }
              });
          } else {
            if (this.engine) {
              this.engine.onCtrlEvent(controlname, action, data);
            }
          }
        } else {
          LogUtil.warn('部件名称或者行为异常');
        }
        break;
    }
  }

  /**
   * @description 处理工具栏点击事件
   * @param {string} tag 标识
   * @param {*} event 事件源
   * @return {*}
   * @memberof AppViewControllerBase
   */
  public handleToolBarClick(tag: string, event: MouseEvent) {
    if (App.getEnvironment() && App.getEnvironment()?.isPreviewMode) {
      return;
    }
    const appViewLogic: IPSAppViewLogic | null = this.viewInstance.findPSAppViewLogic(tag);
    const UIDataParam: IUIDataParam = this.getUIDataParam(this.getDatas());
    Object.assign(UIDataParam, { event: event });
    const UIEnvironmentParam: IUIEnvironmentParam = this.getUIEnvironmentParam();
    Object.assign(UIEnvironmentParam, { ctrl: this.ctrlRefsMap.get(this.xDataControlName) });
    AppViewLogicUtil.executeViewLogic(appViewLogic, UIDataParam, UIEnvironmentParam, this.viewCtx);
  }

  /**
   * @description 视图刷新
   * @param {*} [arg] 刷新参数
   * @memberof AppViewControllerBase
   */
  public refresh(arg?: any): void {
    if (this.xDataControlName) {
      this.viewState.next({ tag: this.xDataControlName?.toLowerCase(), action: 'refresh', data: arg });
    }
    this.hooks.refresh.callSync({ arg: arg });
  }

  /**
   * @description 关闭视图
   * @param {*} [args] 关闭参数
   * @memberof AppViewControllerBase
   */
  public closeView(args?: any) {
    this.hooks.closeView.callSync({ arg: args });
  }

  /**
   * @description 初始化快速分组
   * @memberof AppViewControllerBase
   */
  public async initQuickGroup() {}

  /**
   * @description 初始化视图逻辑
   * @memberof AppViewControllerBase
   */
  public async initViewLogic() {
    if (
      this.viewInstance.getPSAppViewLogics() &&
      (this.viewInstance.getPSAppViewLogics() as IPSAppViewLogic[]).length > 0
    ) {
      (this.viewInstance.getPSAppViewLogics() as IPSAppViewLogic[]).forEach((element: any) => {
        // 目标逻辑类型类型为实体界面逻辑、系统预置界面逻辑、前端扩展插件、脚本代码
        if (
          element &&
          element.logicTrigger &&
          (Object.is(element.logicType, 'DEUILOGIC') ||
            Object.is(element.logicType, 'SYSVIEWLOGIC') ||
            Object.is(element.logicType, 'PFPLUGIN') ||
            Object.is(element.logicType, 'SCRIPT'))
        ) {
          switch (element.logicTrigger) {
            case 'TIMER':
              this.viewTriggerLogicMap.set(element.name.toLowerCase(), new AppTimerEngine(element));
              break;
            case 'CTRLEVENT':
              if (element?.getPSViewCtrlName() && element?.eventNames) {
                this.viewTriggerLogicMap.set(
                  `${element.getPSViewCtrlName()?.toLowerCase()}-${element.eventNames?.toLowerCase()}`,
                  new AppCtrlEventEngine(element),
                );
              }
              break;
            case 'VIEWEVENT':
              if (element?.eventNames) {
                this.viewTriggerLogicMap.set(`${element.eventNames?.toLowerCase()}`, new AppViewEventEngine(element));
              }
              break;
            default:
              LogUtil.log(`视图${element.logicTrigger}类型暂未支持`);
              break;
          }
        }
        // 绑定用户自定义事件
        if (element.eventNames && element.eventNames.toLowerCase().startsWith('_')) {
          const eventName = element.eventNames.toLowerCase().slice(1);
          this.on(eventName, (...args: any) => {
            this.handleViewCustomEvent(element.eventNames?.toLowerCase(), null, args);
          });
        }
      });
    }
  }

  /**
   * @description 处理视图自定义事件
   * @param {string} name 事件名
   * @param {*} data 数据
   * @param {*} args 额外参数
   * @memberof AppViewControllerBase
   */
  public handleViewCustomEvent(name: string, data: any, args: any) {
    if (this.viewTriggerLogicMap.get(name)) {
      const tempUIDataParam: IUIDataParam = this.getUIDataParam(data);
      Object.assign(tempUIDataParam, { args: args });
      this.viewTriggerLogicMap
        .get(name)
        .executeAsyncUILogic({ arg: tempUIDataParam, utils: this.viewCtx, environments: this.getUIEnvironmentParam() });
    }
  }

  /**
   * @description 处理视图定时器逻辑
   * @memberof AppViewControllerBase
   */
  public handleTimerLogic() {
    if (this.viewTriggerLogicMap && this.viewTriggerLogicMap.size > 0) {
      for (const item of this.viewTriggerLogicMap.values()) {
        if (item && item instanceof AppTimerEngine) {
          const tempUIDataParam: IUIDataParam = this.getUIDataParam(null);
          item.executeAsyncUILogic({
            arg: tempUIDataParam,
            utils: this.viewCtx,
            environments: this.getUIEnvironmentParam(),
          });
        }
      }
    }
  }

  /**
   * @description 销毁视图定时器逻辑
   * @memberof AppViewControllerBase
   */
  public destroyLogicTimer() {
    if (this.viewTriggerLogicMap && this.viewTriggerLogicMap.size > 0) {
      for (const item of this.viewTriggerLogicMap.values()) {
        if (item && item instanceof AppTimerEngine) {
          item.destroyTimer();
        }
      }
    }
  }

  /**
   * @description 视图事件 抛出
   * @param {string} action 抛出行为
   * @param {IParam} data 抛出数据
   * @memberof AppViewControllerBase
   */
  public viewEvent(action: string, data?: IParam) {
    this.hooks.event.callSync({
      viewName: this.viewInstance.codeName,
      action: action,
      data: data,
    });
  }
}
